package logic

import (
	"cart/model/cache"
	"context"
	"fmt"
	"strconv"

	"cart/cartrpc/cartrpc"
	"cart/cartrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *cartrpc.CartListRequest) (*cartrpc.CartListResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("Keys:%d", in.UserId)
	KeyS := cache.Rdb.Keys(l.ctx, key).Val()
	if len(KeyS) == 0 {
		return nil, fmt.Errorf("购物车为空")
	}

	total := 0
	var Shoplist []*cartrpc.CartList

	for _, k := range KeyS {
		cartMap := cache.Rdb.HGetAll(l.ctx, k).Val()
		price, _ := strconv.Atoi(cartMap["Price"])
		num, _ := strconv.Atoi(cartMap["Num"])

		sub := price * num
		total += sub

		list := cartrpc.CartList{
			ShopName: cartMap["ShopName"],
			Price:    float32(price),
			Image:    cartMap["Image"],
			Status:   cartMap["Status"],
			Num:      int64(num),
		}
		Shoplist = append(Shoplist, &list)
	}

	return &cartrpc.CartListResponse{
		List:  Shoplist,
		Total: float32(total),
	}, nil
}
